<?php

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Articles extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $guarded = [];

    const HOT_NUMBER = 15;

    /**
     * 文章标签
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function tags(){
        return $this->belongsToMany(Tag::class ,'articles_tags','articles_id','tag_id');
    }

    public function getList()
    {
        // 开启执行日志
        \DB::connection()->enableQueryLog();

        $pageSize = empty($params['page_size']) ? config('sdblog.pageSize') : $params['page_size'];
        $page = empty($params['page']) ? 1 : $params['page'];
        return $this->with(["tags"])
            ->orderBy('created_at', "desc")
            ->paginate($pageSize, ["*"], 'page', $page);
    }

    public function getArchive()
    {
        return $this->select("id", "title", DB::raw('date_format(created_at, "%Y") as day'))
            ->enable()
            ->get();
    }

    public function changeEnable($id, $status)
    {
        return $this->where("id", $id)->update(["is_enable" => $status]);
    }

    public function getHotArticles()
    {
        return $this->enable()->orderBy("view_count", "desc")->limit(config("sdblog.dashboard_num"))->get()->toArray();
    }

}
